//
//  ChannelSearchViewController.m
//  BuffetNews
//
//  Created by 李荃荃 on 14-11-6.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ChannelSearchViewController.h"
#import "SecondViewController.h"
#import "TwoTableViewCell.h"
#import "Channel.h"
#import "NightModel.h"
#import "WebColor.h"

@interface ChannelSearchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) NSMutableArray *showArray;  //  显示的数组（搜索结果）
@property (nonatomic, retain) NSMutableArray *showModelArr; //  存放显示的元素的model类
@end

@implementation ChannelSearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.showArray = [NSMutableArray array];
        self.modelArr = [NSMutableArray array];
        self.showModelArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //  判断夜间模式
    if ([NightModel shareInstance].open == 1) {
        self.tableView.backgroundColor = [WebColor dimGray];
    } else {
        self.tableView.backgroundColor = [UIColor whiteColor];
    }
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
//    [self.searchBar becomeFirstResponder];
    [self.searchBar setShowsCancelButton:YES animated:YES];
    [self.searchBar sizeToFit];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"搜索频道";

    [self.view addSubview:self.searchBar];
    [_searchBar release];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.showArray removeAllObjects];//  在进行查找时，将数组清空
    
    //  遍历传进来的大数组，根据block_title查找
    for (NSDictionary *dic in self.bigArr) {
        NSString *string = [dic objectForKey:@"block_title"];
//         NSLog(@"******   %@", string);
        NSRange range = [string rangeOfString:searchText];
        if (range.length != 0) {
            Channel *channel = [[Channel alloc] init];
            channel.title = [dic objectForKey:@"block_title"];
            
            for (Channel *model in self.modelArr) {
                if ([model.title isEqualToString:channel.title]) {
                    channel.result = model.result;
                    break;
                } else {
                    channel.result = NO;
                }
            }
            
            
            
            [self.showModelArr addObject:channel];  //  将符合条件的model元素添加到要显示在tshowModelArr数组上；
            
            [self.showArray addObject:dic];//  将符合条件的元素添加到要显示在tableView上的数组上；
        }
        [self.tableView reloadData];//   刷新tableView
    }
}


- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
//    [self.navigationController popViewControllerAnimated:NO];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.showArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    if (cell == nil) {
        cell = [[[TwoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool"] autorelease];
    }
    
//    NSString *string = [self.showArray[indexPath.row] objectForKey:@"block_title"];
    Channel *channel = self.showModelArr[indexPath.row];
    cell.label1.text = channel.title;
    if (channel.result == YES) {
        [cell.addbutton setBackgroundImage:[UIImage imageNamed:@"iconfont-duihao-2.png"] forState:UIControlStateNormal];
    } else {
        [cell.addbutton setBackgroundImage:[UIImage imageNamed:@"iconfont-circularframejiahao.png"] forState:UIControlStateNormal];
    }

    
    [cell.addbutton addTarget:self action:@selector(buttonChoose:) forControlEvents:UIControlEventTouchUpInside];
    cell.addbutton.tag = indexPath.row;

    //  判断夜间模式是否开启
    if ([NightModel shareInstance].open == 1) {
        cell.backgroundColor = [WebColor dimGray];
    } else {
        cell.backgroundColor = [UIColor whiteColor];
    }
    return cell;
}
- (void)buttonChoose:(UIButton *)button
{
    if ([button.currentBackgroundImage isEqual:[UIImage imageNamed:@"iconfont-circularframejiahao.png"]]) {
        
        Channel *channel = self.modelArr[button.tag];
        channel.result = YES;
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-duihao-2.png"] forState:UIControlStateNormal];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"rootAdd" object:self.showArray[button.tag]];
        
        
    } else{
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-circularframejiahao.png"] forState:UIControlStateNormal];
        Channel *channel = self.modelArr[button.tag];
        channel.result = NO;
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"rootDelete" object:self.showArray[button.tag]];
    }

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = [self.showArray[indexPath.row] objectForKey:@"api_url"];
    SecondViewController *secondVC = [[SecondViewController alloc] init];
    secondVC.apiString = string;
    [secondVC setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
    [self presentViewController:secondVC animated:YES completion:^{
        
    }];
}


- (void)dealloc
{
    [_bigArr release];
    [_tableView release];
    [_searchBar release];
    [_showArray release];
    [_showModelArr release];
    [_modelArr release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
